<template>

  <div>
    <div class="w">
      <!-- 标题 -->
      <div class="title-area">
        <span>
          评测用例信息
        </span>
      </div>

      <!-- 主体内容显示区 -->
      <div class="content-area">

        <!-- 查询表单区 -->
        <div class="form-area">
          <Form
            name="form"
            ref="formRef"
            :labelCol="{span: 4, offset: 0}"
            :initialValues="form"
            @finish="formFinish">

            <Row :gutter="5">
              <FormItem name="reviewCaseNumber" label="用例代码">
                <Input style="width: 70%" disabled />
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="reviewCaseName" label="用例名称" :rules="formRules.reviewCaseName">
                <Input placeholder="请输入用例名称" style="width: 70%" />
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="reviewCaseType" label="用例类型" :rules="formRules.reviewCaseType" style="position: relative;" class="reviewCaseTypePopupContainer">
                <Select placeholder="请选择用例类型" style="width: 70%" :getPopupContainer="getReviewCaseTypePopupContainer">
                  <Option v-for="type in refData.caseTypes" :key="type.value" :value="type.value" :label="type.label" />
                </Select>
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="usefor" label="适用场景" :rules="formRules.usefor">
                <TextArea placeholder="请输入适用场景" style="width: 70%; height: 100px;" />
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="remark" label="用例描述" :rules="formRules.remark">
                <TextArea placeholder="请输入用例描述" style="width: 70%; height: 100px;" />
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="input" label="输入">
                <TextArea placeholder="请输入内容" style="width: 70%; height: 100px;" />
              </FormItem>
            </Row>
            <Row :gutter="5">
              <FormItem name="output" label="期待输出">
                <TextArea placeholder="请输入期待输出" style="width: 70%; height: 100px;" />
              </FormItem>
            </Row>
          </Form>
        </div>
      </div>
    </div>

    <div class="w" style="margin-top: 5px;">
      <!-- 标题 -->
      <div class="title-area">
        <span>
          用例脚本
        </span>
      </div>

      <!-- 操作按钮 -->
      <Button type="primary" style="position: absolute; top: 2px; right: 25px;" @click="addNewCaseScript">
        <Icon name="add-new" style="margin-top: 4px;" /> 新增脚本
      </Button>

      <!-- 主体内容显示区 -->
      <div class="content-area">
        <Table
          :columns="tableColumns"
          :dataSource="tableData"
          :bordered="false"
          :rowKey="(record) => record.key"
          :pagination="false">

          <template #render="render">
            <div v-if="render.dataIndex == 'id'">
              {{ render.index + 1 }}
            </div>
            <div v-else-if="render.dataIndex == 'remark'">
              <Input placeholder="请输入脚本描述" style="width: 100%;" v-model="render.record.remark" />
            </div>
            <div v-else-if="render.dataIndex == 'scriptFile'">
               <Upload v-model="render.record.scriptFile" uploadText="选取文件" :fileType="['doc', 'docx', 'pdf']" :fileSize="100" :limit="1"></Upload>
            </div>
            <div v-else-if="render.dataIndex == 'readmeFile'">
               <Upload v-model="render.record.readmeFile" uploadText="选取文件" :fileType="['doc', 'docx', 'pdf']" :fileSize="100" :limit="1"></Upload>
            </div>
            <div v-else-if="render.dataIndex == 'operation'">
              <a href="#" @click="moveCaseScript(render.index, true)" :disabled="render.index <= 0"><Icon name="arrow-up" style="margin-top: 4px;" /></a>
              <span> </span>
              <a href="#" @click="moveCaseScript(render.index, false)" :disabled="render.index >= tableData.length - 1"><Icon name="arrow-down" style="margin-top: 4px;" /></a>
              <Button type="link" size="sm" @click="removeCaseScript(render.index)">删除</Button>
            </div>
          </template>
        </Table>

        <Row style="margin-top: 20px;">
          <Col :span="12" :offset="9">
            <Button style="width: 100px;" type="primary" @click="formValidate">提 交</Button>
            <Button style="width: 100px; margin-left: 20px;" @click="formCancel">取 消</Button>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 提交确认框 -->
    <Modal title="提交确认" v-model="isModalVisible" @ok="formSubmit" @cancel="isModalVisible = false" centered>
      <p>即将提交评测用例信息，是否确认？</p>
    </Modal>
  </div>
</template>

<script>
import * as ruoyi from '@/utils/ruoyi'
import { Message } from '@uni/vue';
import { getCase, addCase, updateCase } from "@/api/docase/reviewcase";
import Upload from '@/components/upload'
export default {
  name: "app",
  components: {
    Upload
  },
  props: {
    reviewCaseId: {
      type: Number,
      default: 0
    },
    currRow: {
      default: () => {}
    },
    refData: {
      default: () => {}
    }
  },
  data: function () {
    const validateCaseType = (rule, value) => {
      let type = this.refData.caseTypes.find(type => type.value == value);
      if (type) return Promise.resolve();
      else return Promise.reject("请选择用例类型");
    };
    return {
      tableColumns: [
        {"title":"序号", "dataIndex":"id", "key":"id","align":"center", width: 50},
        {"title":"脚本描述", "dataIndex":"remark", "key":"remark"},
        {"title":"脚本文件", "dataIndex":"scriptFile", "key":"scriptFile","align":"center", width: 300},
        {"title":"说明文件", "dataIndex":"readmeFile", "key":"readmeFile","align":"center", width: 300},
        {"title":"操作", "dataIndex":"operation", "key":"operation","align":"center", width: 90},
      ],
      tableData: [],
      form: {
        reviewCaseNumber: this.reviewCaseId ? this.currRow.reviewCaseNumber : `RC${this.getCurrentTime()}`,
        reviewCaseName: this.currRow.reviewCaseName,
        reviewCaseType: `${this.currRow.reviewCaseType ? this.currRow.reviewCaseType : ''}`,
        usefor: this.currRow.usefor,
        remark: this.currRow.remark,
        input: this.currRow.input,
        output: this.currRow.output,
        reviewCaseScriptList: []
      },
      formRules: {
        reviewCaseName: [
          { required: true, message: '请输入用例名称' },
        ],
        reviewCaseType: [
          // { required: true, message: '请选择用例类型' },
          { required: true, validator: validateCaseType },
        ],
        usefor: [
          { required: true, message: '请输入适用场景' },
        ],
        remark: [
          { required: true, message: '请输入用例描述' },
        ]
      },
      isModalVisible: false
    }
  },
  mounted: function () {
    // console.log("mounted reviewCaseId: ", this.reviewCaseId);
    // console.log("mounted currRow: ", this.currRow);
    // console.log("mounted refData: ", this.refData);

    if (this.reviewCaseId !== 0) this.queryCaseDetail();
  },
  methods: {
    getReviewCaseTypePopupContainer: function () {
      return document.querySelector('.reviewCaseTypePopupContainer');
    },
    queryCaseDetail: async function () {
      const rs = await getCase(this.reviewCaseId);
      if (rs.code !== 200) return Message.error({ text: '获取评测用例明细失败：' + rs.msg });
      this.form = rs.data;
      this.tableData = this.form.reviewCaseScriptList;
    },
    formValidate: function () {
      this.$refs.formRef.submit();
    },
    formCancel: function () {
      // this.$refs.formRef.reset();
      this.handleCancel();
    },
    formFinish: function (formValues) {
      this.form = formValues;
      // this.isModalVisible = true;
      this.formSubmit();
    },
    formSubmit: async function () {
      // 公共属性
      this.form.createBy = this.$store.state.user.name;
      this.form.createTime = ruoyi.parseTime(Date.now());
      this.form.updateBy = this.$store.state.user.name;
      this.form.updateTime = ruoyi.parseTime(Date.now());

      // 提交表单请求
      this.isModalVisible = false;
      let reqForm = JSON.parse(JSON.stringify(this.form));
      reqForm.reviewCaseScriptList = this.tableData;
      // console.log("reqForm: ", reqForm);

      if (this.reviewCaseId) {
        // 修改
        reqForm.reviewCaseId = this.reviewCaseId;
        const rs = await updateCase(reqForm);
        if (rs.code !== 200) return Message.error({ text: '修改评测用例失败：' + rs.msg });
        Message.success({ text: '修改评测用例完成' });
        this.handleCancel();

      } else {
        // 新增
        const rs = await addCase(reqForm);
        if (rs.code !== 200) return Message.error({ text: '新增评测用例失败：' + rs.msg });
        Message.success({ text: '新增评测用例完成' });
        this.handleCancel();
      }
    },
    addNewCaseScript: function () {
      this.tableData.push({
        remark: '',
        scriptFile: '',
        readmeFile: ''
      });
    },
    moveCaseScript: function (index, isMoveUp) {
      let finalIndex = isMoveUp ? index - 1 : index + 1;
      let rowFrom = JSON.parse(JSON.stringify(this.tableData[index]));
      let rowTo = JSON.parse(JSON.stringify(this.tableData[finalIndex]));

      this.$set(this.tableData, index, rowTo);
      this.$set(this.tableData, finalIndex, rowFrom);
    },
    removeCaseScript: function (index) {
      this.tableData.splice(index, 1);
      // console.log('removeCaseScript: ', this.tableData);
    },
    handleCancel: function () {
      this.$emit('handleCancel');
    }
  }
}
</script>

<style scoped>
  .w {
    /* height: 100%; */
    position: relative;
    background-color: #F9FAFB;
  }

  /* 标题 */
  .title-area {
    height: 36px;
    background-color: #E9EBF0;
  }
  .title-area span {
    display: inline-block;
    font-weight: 500;
    line-height: 36px;
    margin-left: 15px;
  }

  /* 主体内容显示区 */
  .content-area {
    /* background-color: lightblue; */
    height: 100%;
    margin-top: 15px;
    margin-left: 25px;
    margin-right: 25px;
    padding-bottom: 15px;
  }

  /* 查询表单区 */
  .form-area {
    /* background-color: lightcyan; */
    margin-left: 50px;
    margin-right: 50px;
  }
  .formGrid {
    /* background-color: orange; */
    margin-top: 15px;
    height: 35px;
    line-height: 35px;
  }

  .uni-divider {
    margin: 0;
  }

  /* 按钮区 */
  .button-area {
    margin-top: 15px;
    /* background-color: lightcyan; */
  }
  .button-area svg {
    margin-top: 3px;
    margin-right: 5px;
  }

  /* 列表区 */
</style>

